<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="query.phone" class="filter-item w-200" placeholder="手机号码" size="medium" />
            <el-input v-model="query.name" class="filter-item w-200" placeholder="姓名" size="medium" />
            <el-select v-model="query.source_from" clearable class="filter-item w-200" placeholder="来源" size="medium">
                <el-option v-for="item in sources" :key="item.index" :value="item.index" :label="item.label"></el-option>
            </el-select>
            <el-select class="w-200 filter-item" size="medium" v-model="query.role_id" clearable filterable placeholder="用户角色">
                <el-option v-for="item in userRoles" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
            <el-select class="w-200 filter-item" size="medium" v-model="query.school_id" clearable filterable placeholder="学校">
                <el-option v-for="item in schools" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
            <el-button  class="filter-item"  icon="el-icon-search" @click="fetchList(resetPage = true)" size="medium">搜索</el-button>
            <el-button class="filter-item" type="primary" icon="el-icon-plus" size="medium" style="float: right" @click="showAdd()" v-permission="'users.store'">新 增</el-button>
        </div>
        <el-table :data="users" v-loading="visible.listLoading" border stripe>
            <el-table-column label="#" align="center" width="100px">
                <template slot-scope="scope">
                    {{ query.size * (query.page - 1) + scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="id" prop="id" align="center" width="100px;"></el-table-column>
            <el-table-column label="姓名" prop="name" align="center"></el-table-column>
            <el-table-column label="手机号码" prop="phone" align="center"></el-table-column>
            <el-table-column label="状态" prop="status" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-check" v-if="scope.row.status === 1" />
                    <i class="el-icon-close" v-else />
                </template>
            </el-table-column>
            <el-table-column label="角色名称" prop="role.name" align="center"></el-table-column>
            <el-table-column label="学校" prop="school.name" align="center"></el-table-column>
            <el-table-column label="来源" prop="source_format" align="center"></el-table-column>
            <el-table-column label="早餐规则" prop="morning_rule" align="center">
                <template slot-scope="scope">
                    {{ scope.row.morning_rule === 1 ? '自动' : '手动' }}
                </template>
            </el-table-column>
            <el-table-column label="午餐规则" prop="lunch_rule" align="center">
                <template slot-scope="scope">
                    {{ scope.row.lunch_rule === 1 ? '自动' : '手动' }}
                </template>
            </el-table-column>
            <el-table-column label="晚餐规则" prop="dinner_rule" align="center">
                <template slot-scope="scope">
                    {{ scope.row.dinner_rule === 1 ? '自动' : '手动' }}
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="created_at" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button class="filter-item" icon="el-icon-edit" type="primary" size="mini" v-permission="'users.update'" @click="showEdit(scope.row)">编 辑</el-button>
                    <el-button class="filter-item" type="danger" size="mini" v-permission="'users.destroy'" @click="showChange(scope.row)">{{ scope.row.status === 1 ? '禁用' : '启用' }}</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="query.page"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="query.size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <el-dialog :title="formTitle" :visible.sync="visible.form" width="700px" @close="$refs['form'].resetFields()">
            <el-form :model="form" ref="form" label-width="120px" :rules="rules">
                <el-form-item label="姓名" prop="name" verify required>
                    <el-input v-model="form.name" placeholder="请输入昵称" />
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="form.phone" placeholder="请输入手机号码" />
                </el-form-item>
                <el-form-item label="学校" prop="school_id" verify required>
                    <el-select class="form-select" v-model="form.school_id" filterable placeholder="请选择学校" @change="changeSchool">
                        <el-option v-for="item in schools" :key="item.id" :value="item.id" :label="item.name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="用户角色" prop="role_id" verify required>
                    <el-select class="form-select" v-model="form.role_id" filterable placeholder="请选择用户角色">
                        <el-option v-for="item in userRoles" :key="item.id" :value="item.id" :label="item.name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="学号/教工号" prop="user_no">
                    <el-input v-model="form.user_no" placeholder="请输入学号/教工号" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select class="form-select" v-model="form.sex" placeholder="请选择性别">
                        <el-option v-for="item in sexs" :key="item.index" :value="item.index" :label="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="visible.form = false, $refs['form'].resetFields()">取 消</el-button>
                <el-button type="primary"  @click="handleForm" :loading="visible.formLoading">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
  import { fetchUsers, addUsers, editUsers, changeUsers } from '@/api/user'
  import { fetchData } from '@/api/data'
  import { isPhoneAvailable } from '@/utils/validate'
  export default {
    name: 'user_list',
    data() {
      const validPhone = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入电话号码'))
        } else if (!isPhoneAvailable(value)) {
          callback(new Error('请输入正确的11位手机号码'))
        } else {
          callback()
        }
      }
      return {
        query: {
          phone: null,
          source_from: null,
          name: null,
          role_id: null,
          school_id: null,
          size: 10,
          page: 1
        },
        visible: {
          formLoading: false,
          listLoading: false,
          form: false
        },
        form: {
          name: '',
          phone: '',
          role_id: '',
          user_no: '',
          sex: '',
          school_id: ''
        },
        sexs: [
          {
            index: 1,
            label: '男'
          },
          {
            index: 2,
            label: '女'
          }
        ],
        users: [],
        userRoles: [],
        schools: [],
        total: 0,
        editRow: '',
        formTitle: '',
        formType: '',
        sources: [
          {
            index: 'backend',
            label: '后台添加'
          },
          {
            index: 'school',
            label: '学校同步'
          },
          {
            index: 'import',
            label: '后台导入'
          }
        ],
        rules: {
          phone: [
            { required: true, trigger: ['blur', 'change'], validator: validPhone }
          ]
        },
        msg: ''
      }
    },
    methods: {
      // 切换学校更换用户角色
      changeSchool() {
        fetchData({ sources: ['getSchoolUserRoles'], school_id: this.form.school_id }).then(res => {
          this.userRoles = res.getSchoolUserRoles
        })
      },
      handleSizeChange(size) {
        this.query.size = size
        this.fetchList()
      },
      handleCurrentChange(page) {
        this.query.page = page
        this.fetchList()
      },
      fetchList(resetPage = false) {
        if (resetPage === true) {
          this.query.page = 1
        }
        this.visible.listLoading = true
        fetchUsers(this.query).then(res => {
          this.users = res.data
          this.total = res.meta.total
          this.visible.listLoading = false
        })
      },
      showAdd() {
        Object.assign(this.form, this.$options.data().form)
        this.visible.form = true
        this.formTitle = '新增用户'
        this.formType = 'add'
      },
      showEdit(row) {
        Object.existAssign(this.form, row)
        this.editRow = row
        this.visible.form = true
        this.formTitle = '编辑用户'
        this.formType = 'edit'
      },
      showChange(row) {
        this.msg = row.status === 1 ? '禁用' : '启用'
        this.$confirm(this.msg + '用户', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          changeUsers(row.id).then(res => {
            row.status = res.status
            this.$message.success(this.msg + '成功')
          })
        }).catch(err => {
          this.$handleNotFound(err, '用户不存在')
        })
      },
      handleForm() {
        this.$refs.form.validate().then(valid => {
          if (valid) {
            this.visible.formLoading = true
            if (this.formType === 'add') {
              addUsers(this.form).then(res => {
                this.fetchList()
                this.visible.form = false
                this.$message.success('新增成功')
                this.visible.formLoading = false
              }).catch(err => {
                this.$handleNotFound(err)
                this.visible.formLoading = false
              })
            } else {
              editUsers(this.form, this.editRow.id).then(res => {
                this.fetchList()
                this.visible.form = false
                this.$message.success('编辑成功')
                this.visible.formLoading = false
              }).catch(err => {
                this.$handleNotFound(err, '用户不存在')
                this.visible.formLoading = false
              })
            }
          }
        }).catch(() => {})
      }
    },
    created() {
      this.fetchList()
      fetchData({ sources: ['schools'] }).then(res => {
        this.schools = res.schools
      })
    }
  }
</script>

<style scoped lang="scss">
    .form-select{
        width: 100%;
    }
    .el-icon-check{
        color: green;
    }
    .el-icon-close{
        color: red;
    }
</style>
